<?php

/**
 * Controller_install
 */


class Controller_Install extends MyApp {
	function __construct ()
	{
		parent::__construct();
		$this->lock = "install/install.lock";

		// 检测本地是否已有lock文件
		if (file_exists($this->lock)){
			exit("请勿重复安装");
		}

	}


	/** 开始  **/
	public function actionStart()
	{



		if ($_POST){


			$op = $this->post->op;
			if ($op !='1'){
				exit("请同意协议");
			}


			// 跳转到配置页
			Helper_Client::reurl("index.php?a=install.config");exit();

		}

		$this->tpl->display("install/install.start.tpl.php");
	}


	/** 配置 **/
	public function actionConfig()
	{
		if ($_POST){
			// 数据库连接部分
			$db_host     = $this->post->db_host;
			$db_root     = $this->post->db_root;
			$db_password = $this->post->db_password;
			$db_name     = $this->post->db_name;

			// 尝试连接
			$this->link_id = @mysql_connect($db_host, $db_root, $db_password, 1);
			if (!$this->link_id)
			{
				// 连接错误
				exit("数据库连接错误");
			}
				// 创建数据库
			mysql_query("create database {$db_name}", $this->link_id);



			// 加入配置文件
			include (CONFIG_PATH.'testcommon.inc.php');
			// 加载db类
			$this->db    = YOU::loadLib('db', $db_ini);


			// 写入sql文件
			$sql = file_get_contents("install/sql.txt");

			$this->db->query($sql);

			// 写入配置文件
			$cf = file_get_contents("install/inc.txt");
			$cf = str_replace("cf_dbhost", $db_host, $cf);
			$cf = str_replace("cf_dbuser", $db_root, $cf);
			$cf = str_replace("cf_dbpwd", $db_password, $cf);
			$cf = str_replace("cf_dbname", $db_name, $cf);
			$cf = str_replace("cf_rootpath", $_SERVER['DOCUMENT_ROOT']."/public", $cf);			
			file_put_contents("include/testcommon.inc.php", $cf);

			// 写入文件锁
			file_put_contents($this->lock, date("Y-m-d H:i:s"));

			// 创建管理员
			$admin_name     = $this->post->admin_name;
			$admin_password = $this->post->admin_password;

			$info = array(
			"user_name"     => $admin_name,
			"user_password" => md5($admin_password),
			"user_type"     => "admin",
			);
			
			$this->db->do_insert("tbl_user", $info);

			// 跳转
			Helper_Client::reurl("index.php?a=install.success");exit();


		}
		$this->tpl->display("install/install.config.tpl.php");
	}

	/** 结束  **/
	public function actionSuccess()
	{

		$this->tpl->display("install/install.success.tpl.php");
	}

}